package com.xu.cloud.auth.service.impl;

import com.xu.cloud.auth.component.UserInfoComponent;
import com.xu.cloud.auth.component.oauth.OAuth2ExecutionChain;
import com.xu.cloud.auth.enums.ThirdPartyEnum;
import com.xu.cloud.auth.exception.AuthErrorCodeEnum;
import com.xu.cloud.auth.pojo.bo.OAuth2UserInfo;
import com.xu.cloud.auth.pojo.domain.UserInfoDO;
import com.xu.cloud.auth.service.OAuth2Service;
import com.xu.cloud.common.util.AssertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * @author xuguan
 * @since 2025/2/27
 */
@Service
public class OAuth2ServiceImpl implements OAuth2Service {

    @Autowired
    private UserInfoComponent userInfoComponent;
    @Autowired
    private OAuth2ExecutionChain oAuth2ExecutionChain;

    @Nullable
    @Override
    public UserInfoDO queryUserInfoByOauth2(String thirdPartyType, String code) {
        return queryUserInfoByOauth2User(oauth2UserInfo(thirdPartyType, code));
    }

    @Override
    public OAuth2UserInfo oauth2UserInfo(String thirdPartyType, String code) {
        AssertUtil.assertHasText(thirdPartyType);
        AssertUtil.assertHasText(code);
        final ThirdPartyEnum thirdPartyEnum = ThirdPartyEnum.getByThirdPartyType(thirdPartyType);
        AssertUtil.assertNotNull(thirdPartyEnum, AuthErrorCodeEnum.THIRD_PARTY_LOGIN_NOT_SUPPORT.info().newException());
        return oAuth2ExecutionChain.oauth2UserInfo(thirdPartyEnum, code);
    }

    @Nullable
    @Override
    public UserInfoDO queryUserInfoByOauth2User(@Nullable OAuth2UserInfo oAuth2UserInfo) {
        if (Objects.isNull(oAuth2UserInfo)) {
            return null;
        }

        UserInfoDO userInfoDo;
        if (StringUtils.hasText(oAuth2UserInfo.getMobileNo())) {
            userInfoDo = userInfoComponent.queryUserInfoByMobileNo(oAuth2UserInfo.getMobileNo());
            if (Objects.nonNull(userInfoDo)) {
                return userInfoDo;
            }
        }

        if (StringUtils.hasText(oAuth2UserInfo.getEmail())) {
            userInfoDo = userInfoComponent.queryUserInfoByLoginName(oAuth2UserInfo.getEmail());
            if (Objects.nonNull(userInfoDo)) {
                return userInfoDo;
            }
        }

        return null;
    }
}
